package me.zhengjie.pay.rest;

import com.wechat.pay.java.service.refund.model.*;
import me.zhengjie.annotation.rest.AnonymousGetMapping;
import me.zhengjie.config.WechatPayConfig;
import me.zhengjie.pay.domain.JjzhWxPayOrders;
import me.zhengjie.pay.service.JjzhWxPayOrdersService;
import me.zhengjie.utils.OrderNoGenerator;
import me.zhengjie.weixin.WxRefundUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/api/wxpay")
public class WxRefundController {
    private static final Logger logger = LoggerFactory.getLogger(WxRefundController.class);

    @Autowired
    private WechatPayConfig wechatPayConfig;

    @Autowired
    private JjzhWxPayOrdersService jjzhWxPayOrdersService;

    /**
     * 发起退款请求
     *
     * @param request HttpServletRequest 用于获取请求参数
     * @return ResponseEntity 返回操作结果
     */
    @GetMapping("/refund")
    public ResponseEntity<Object> refund(HttpServletRequest request) {

        String orderNo = request.getParameter("orderNo");
        logger.info("开始处理退款请求，订单号：{}", orderNo);

        // 查询订单
        JjzhWxPayOrders order = jjzhWxPayOrdersService.findByOrderNo(orderNo);
        if (order == null) {
            logger.error("退款失败：订单不存在，订单号：{}", orderNo);
            throw new RuntimeException("订单不存在");
        }

        logger.info("订单查询成功，订单号：{}，微信订单号：{}", orderNo, order.getTransactionId());

        // 获取必要的订单信息
        String transactionId = order.getTransactionId();
        Long amount = order.getAmount();
        Long total = amount;
        String subMchid = order.getSubMchind();
        String reason = "退款请求"; // 退款原因可以根据实际需求修改

        // 生成商户退款单号
        String outRefundNo = OrderNoGenerator.generate();

        // 发起退款查询
        Refund response;
        try {
            response = WxRefundUtil.refundQuery(wechatPayConfig,outRefundNo , subMchid, transactionId, reason, amount, total);
            logger.info("退款请求已发起，订单号：{}，退款状态：{}", orderNo, response.getStatus());
        } catch (Exception e) {
            logger.error("退款请求失败，订单号：{}，错误信息：{}", orderNo, e.getMessage(), e);
            return new ResponseEntity<>("退款请求失败，请稍后重试", HttpStatus.INTERNAL_SERVER_ERROR);
        }

        // 处理退款状态
        Status status = response.getStatus();
        String msg = "操作成功,当前订单状态:";
        long staL = 3; // 默认退款成功

        switch (status) {
            case SUCCESS:
                msg += "退款成功";
                logger.info("退款成功，订单号：{}", orderNo);
                String successTime = response.getSuccessTime();
                try {
                    // 解析成功时间
                    OffsetDateTime odt = OffsetDateTime.parse(successTime, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
                    Timestamp timestamp = Timestamp.from(odt.toInstant());
                    order.setRefundTime(timestamp);
                    staL = 3;
                    logger.info("退款成功，订单号：{}，退款时间：{}", orderNo, timestamp);
                } catch (Exception e) {
                    logger.error("退款成功时间解析失败，订单号：{}", orderNo, e);
                }
                break;
            case PROCESSING:
                msg += "退款处理中";
                staL = 2;
                logger.info("退款处理中，订单号：{}", orderNo);
                break;
            case CLOSED:
                msg += "退款关闭";
                staL = 4;
                logger.warn("退款关闭，订单号：{}", orderNo);
                break;
            case ABNORMAL:
                msg += "退款异常";
                staL = 4;
                logger.error("退款异常，订单号：{}", orderNo);
                break;
        }

        // 更新订单状态
        try {
            order.setStatus(staL);
            order.setOutRefundNo(outRefundNo);
            jjzhWxPayOrdersService.update(order);
            logger.info("订单状态更新成功，订单号：{}，新状态：{}", orderNo, staL);
        } catch (Exception e) {
            logger.error("订单状态更新失败，订单号：{}", orderNo, e);
        }

        return new ResponseEntity<>(msg, HttpStatus.OK);
    }
}
